package cbfg.http

import android.net.ParseException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onEach
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException

/**
 * @author: TomHawk
 * @description:
 * @date: 2024/12/5 9:33
 */


/**
 * 接口请求
 */
suspend fun <T> flowRequest(block: suspend () -> T, callback: ApiCallback<T>) {
    flow {
        val response = block()
        emit(response)
    }.flowOn(Dispatchers.IO)
        .catch {
            callback.onResult(null, it)
        }.onEach {
            callback.onResult(it, null)
        }.collect()
}

/** 获取接口请求出错原因 */
val Throwable.errorMsg: String
    get() = when (this) {
        is HttpException -> "${this.message()}(${this.code()})"

        //is JsonParseException,
        //is MalformedJsonException,
        is JSONException,
        is ParseException -> "数据解析错误"

        is ConnectException,
        is java.net.SocketException,
        is java.net.UnknownHostException,
        is javax.net.ssl.SSLException,
        is java.net.SocketTimeoutException -> "网络异常(${this.javaClass.name})"

        else -> this.message ?: "$this"
    }